// import { GatewayType } from "@/api/interface/iot";
import { getProductList } from "@/api/modules/iot/product";
// import { deptAnonymous } from "@/utils/constants";
import { getCurrentInstance, defineComponent, ComponentInternalInstance } from "vue";
export default defineComponent({
	props: {
		modelValue: [String, Number, Array],
		multiple: Boolean,
		detail: {
			type: Object,
			default() {
				return {};
			}
		}
	},
	emits: ["update:modelValue", "change"],
	setup(props, { emit, expose }) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const state = reactive<any>({
			selected: props.multiple ? [] : "",
			dataList: []
		});
		onMounted(() => {
			init();
		});
		const init = async () => {
			let res = await getProductList({
				pageIndex: 1,
				pageSize: 9999,
				// deviceType: props.detail.id && props.detail.dept == deptAnonymous ? null : props.detail.type
				//修改时，可以将设备修改成网关，也可以将网关修改成设备
				deviceType: props.detail.type == "all" ? null : props.detail.type == "device" ? "device" : null,
				deviceTypeNe: props.detail.type == "all" ? null : props.detail.type == "device" ? null : "device"
			});
			state.dataList = res.result?.records || [];
			if (props.multiple) {
				state.selected = [];
				let arr = props.modelValue as any;
				arr.map((item: any) => {
					state.selected.push({ model: item });
				});
			} else {
				state.selected = { model: props.modelValue };
			}
		};
		const selectEl = ref();
		const change = () => {
			if (props.multiple) {
				emit("update:modelValue", state.selected);
			} else {
				props.detail.productModel = state.selected.model;
				props.detail.defaultType = props.detail.type;
				props.detail.type = state.selected.deviceType;
				emit("update:modelValue", state.selected.model);
			}
			emit("change", state.selected.model);
			selectEl.value.blur();
		};
		expose({ init, state });
		return () => {
			return (
				<div class="w-full">
					<el-select
						ref={selectEl}
						filterable
						class="w-full"
						multiple={props.multiple}
						collapse-tags
						collapse-tags-tooltip
						v-model={state.selected}
						placeholder={proxy?.$t("selectproductlist.placeholder.select")}
						onChange={() => change()}
						value-key="model"
						clearable
					>
						{state.dataList.map((item: any) => {
							return (
								<el-option key={item.id} label={item.name || item.model} value={item}>
									<div class="flex justify-between">
										<div class="pr-4">{item.name || item.model}</div>
										<div class="text-gray-400">{item.model}</div>
									</div>
								</el-option>
							);
						})}
					</el-select>
				</div>
			);
		};
	}
});
